package cn.gzjp.common.utils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.NumberFormat;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class StringUtil implements Serializable {

	public StringUtil() {
	}

	private static final String START = "*";
	private static Random randGen = new Random();

	private static MessageDigest digest = null;

	private static final char LT_ENCODE[] = "&lt;".toCharArray();

	private static final char GT_ENCODE[] = "&gt;".toCharArray();

	private static char numbersAndLetters[] = "0123456789abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
			.toCharArray();

	private static char lowerLetters[] = "abcdefghijklmnopqrstuvwxyz"
			.toCharArray();

	private static char upperLetters[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
			.toCharArray();

	private static Logger log = LoggerFactory.getLogger(StringUtil.class);

	private final static String[] hex = { "00", "01", "02", "03", "04", "05",
			"06", "07", "08", "09", "0A", "0B", "0C", "0D", "0E", "0F", "10",
			"11", "12", "13", "14", "15", "16", "17", "18", "19", "1A", "1B",
			"1C", "1D", "1E", "1F", "20", "21", "22", "23", "24", "25", "26",
			"27", "28", "29", "2A", "2B", "2C", "2D", "2E", "2F", "30", "31",
			"32", "33", "34", "35", "36", "37", "38", "39", "3A", "3B", "3C",
			"3D", "3E", "3F", "40", "41", "42", "43", "44", "45", "46", "47",
			"48", "49", "4A", "4B", "4C", "4D", "4E", "4F", "50", "51", "52",
			"53", "54", "55", "56", "57", "58", "59", "5A", "5B", "5C", "5D",
			"5E", "5F", "60", "61", "62", "63", "64", "65", "66", "67", "68",
			"69", "6A", "6B", "6C", "6D", "6E", "6F", "70", "71", "72", "73",
			"74", "75", "76", "77", "78", "79", "7A", "7B", "7C", "7D", "7E",
			"7F", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89",
			"8A", "8B", "8C", "8D", "8E", "8F", "90", "91", "92", "93", "94",
			"95", "96", "97", "98", "99", "9A", "9B", "9C", "9D", "9E", "9F",
			"A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "AA",
			"AB", "AC", "AD", "AE", "AF", "B0", "B1", "B2", "B3", "B4", "B5",
			"B6", "B7", "B8", "B9", "BA", "BB", "BC", "BD", "BE", "BF", "C0",
			"C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "CA", "CB",
			"CC", "CD", "CE", "CF", "D0", "D1", "D2", "D3", "D4", "D5", "D6",
			"D7", "D8", "D9", "DA", "DB", "DC", "DD", "DE", "DF", "E0", "E1",
			"E2", "E3", "E4", "E5", "E6", "E7", "E8", "E9", "EA", "EB", "EC",
			"ED", "EE", "EF", "F0", "F1", "F2", "F3", "F4", "F5", "F6", "F7",
			"F8", "F9", "FA", "FB", "FC", "FD", "FE", "FF" };

	private final static byte[] val = { 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
			0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
			0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
			0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
			0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x00, 0x01,
			0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x3F, 0x3F, 0x3F,
			0x3F, 0x3F, 0x3F, 0x3F, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x3F,
			0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
			0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
			0x3F, 0x3F, 0x3F, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x3F, 0x3F,
			0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
			0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
			0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
			0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
			0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
			0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
			0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
			0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
			0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
			0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
			0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
			0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
			0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
			0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F };

	private static String localEncode = System.getProperty("file.encoding");

	

	/** */
	/**
	 * 编码
	 * 
	 * @param s
	 * @return
	 */
	public static String escape(String s) {
		StringBuffer sbuf = new StringBuffer();
		int len = s.length();
		for (int i = 0; i < len; i++) {
			int ch = s.charAt(i);
			if ('A' <= ch && ch <= 'Z') {
				sbuf.append((char) ch);
			} else if ('a' <= ch && ch <= 'z') {
				sbuf.append((char) ch);
			} else if ('0' <= ch && ch <= '9') {
				sbuf.append((char) ch);
			} else if (ch == '-' || ch == '_' || ch == '.' || ch == '!'
					|| ch == '~' || ch == '*' || ch == '\'' || ch == '('
					|| ch == ')') {
				sbuf.append((char) ch);
			} else if (ch <= 0x007F) {
				sbuf.append('%');
				sbuf.append(hex[ch]);
			} else {
				sbuf.append('%');
				sbuf.append('u');
				sbuf.append(hex[(ch >>> 8)]);
				sbuf.append(hex[(0x00FF & ch)]);
			}
		}
		return sbuf.toString();
	}

	/** */
	/**
	 * 解码 说明：本方法保证 不论参数s是否经过escape()编码，均能得到正确的“解码”结果
	 * 
	 * @param s
	 * @return
	 */
	public static String unescape(String s) {
		StringBuffer sbuf = new StringBuffer();
		int i = 0;
		int len = s.length();
		while (i < len) {
			int ch = s.charAt(i);
			if ('A' <= ch && ch <= 'Z') {
				sbuf.append((char) ch);
			} else if ('a' <= ch && ch <= 'z') {
				sbuf.append((char) ch);
			} else if ('0' <= ch && ch <= '9') {
				sbuf.append((char) ch);
			} else if (ch == '-' || ch == '_' || ch == '.' || ch == '!'
					|| ch == '~' || ch == '*' || ch == '\'' || ch == '('
					|| ch == ')') {
				sbuf.append((char) ch);
			} else if (ch == '%') {
				int cint = 0;
				if ('u' != s.charAt(i + 1)) {
					cint = (cint << 4) | val[s.charAt(i + 1)];
					cint = (cint << 4) | val[s.charAt(i + 2)];
					i += 2;
				} else {
					cint = (cint << 4) | val[s.charAt(i + 2)];
					cint = (cint << 4) | val[s.charAt(i + 3)];
					cint = (cint << 4) | val[s.charAt(i + 4)];
					cint = (cint << 4) | val[s.charAt(i + 5)];
					i += 5;
				}
				sbuf.append((char) cint);
			} else {
				sbuf.append((char) ch);
			}
			i++;
		}
		return sbuf.toString();
	}

	/**
	 * 将字符从GB2312转为ISO-8859-1
	 * 
	 * @param inFormat
	 *            - 要转换的字符串
	 * @return 转换后的字符串
	 */

	public static String gbToIso(String inFormat) {
		String outFormat = "";

		if (inFormat != null) {
			try {
				// log.info("inFormat:"+inFormat);
				outFormat = new String(inFormat.getBytes("GBK"), "ISO8859-1");
				// log.info("outFormat:"+outFormat);

			} catch (UnsupportedEncodingException errUEE) {

			}
		}

		return outFormat;
	}

	/**
	 * 将字符从ISO-8859-1转为GB2312
	 * 
	 * @param inFormat
	 *            - 要转换的字符串
	 * @return 转换后的字符串
	 */

	public static String isoToGb(String inFormat) {
		String outFormat = "";

		if (inFormat != null) {
			try {
				// log.info("inFormat="+inFormat);
				outFormat = new String(inFormat.getBytes("ISO8859-1"), "GBK");
				// log.info("outFormat="+outFormat);
			} catch (UnsupportedEncodingException errUEE) {

			}
		}

		return outFormat;
	}

	public static String uftToGb(String inFormat) {
		String outFormat = "";

		if (inFormat != null) {
			try {
				outFormat = new String(inFormat.getBytes("utf-8"), "GBK");
			} catch (UnsupportedEncodingException errUEE) {

			}
		}

		return outFormat;
	}

	public static String gbToUtf(String inFormat) {
		String outFormat = "";

		if (inFormat != null) {
			try {
				outFormat = new String(inFormat.getBytes("GBK"), "utf-8");
			} catch (UnsupportedEncodingException errUEE) {

			}
		}

		return outFormat;
	}

	/**
	 * 将字符从ISO8859-1转为utf-8
	 * 
	 * @param inFormat
	 *            - 要转换的字符串
	 * @return 转换后的字符串
	 */
	public static String isoToUtf(String s) {
		if (s == null || s.length() < 0) {
			return "";
		}
		try {
			s = new String(s.getBytes("ISO8859-1"), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return "";
		}
		return s;
	}

	/**
	 * 将字符从UTF-8转为ISO8859-1
	 * 
	 * @param inFormat
	 *            - 要转换的字符串
	 * @return 转换后的字符串
	 */
	public static String utfToIso(String s) {
		if (s == null || s.length() < 0) {
			return "";
		}
		try {
			s = new String(s.getBytes("UTF-8"), "ISO8859-1");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return "";
		}
		return s;
	}

	/**
	 * 转码[local encode -> ISO-8859-1]
	 */
	public static String sysToiso(Object obj) {
		try {
			return (obj == null) ? ""
					: new String(obj.toString().getBytes(localEncode),
							"iso-8859-1");
		} catch (Exception e) {
			return "";
		}
	}

	/**
	 * 转码[local encode -> ISO-8859-1]
	 */
	public static String isoTosys(Object obj) {
		try {
			return (obj == null) ? ""
					: new String(obj.toString().getBytes("iso-8859-1"),
							localEncode);
		} catch (Exception e) {
			return "";
		}
	}

	public static boolean isChiness(String s) {
		String patternstr = "[\\u4e00-\\u9fa5]";
		Pattern p = Pattern.compile(patternstr);
		Matcher m = p.matcher(s);
		return m.find();
	}

	public static boolean isOnlyChinese(String s) {
		String patternstr = "^[\\u4e00-\\u9fa5]+$";
		Pattern p = Pattern.compile(patternstr);
		Matcher m = p.matcher(s);
		return m.find();
	}

	/**
	 * 对传过的String 按length进行拆分
	 * 
	 * @param orgin
	 *            传入的内容
	 * @param length
	 *            每条多长
	 * @return String数组
	 */
	public static String[] toPiece(String orgin, int length) {
		String strGBK = null; // 到得GBK字符串
		char[] strArrayGBK = null; // 得到GBK字符数组
		try {
			strGBK = orgin;
			strGBK = new String(orgin.getBytes(), "GBK"); // 对内容进行GBK编码
			strArrayGBK = strGBK.toCharArray();
		} catch (UnsupportedEncodingException ex) {
		}

		int contentLength = strArrayGBK.length; // 数组长度
		int pieceLength = (contentLength - 1) / length + 1; // 分条数
		String[] result = new String[pieceLength]; // 得到长度的字符串数组

		if (contentLength > 1) {
			int startPiece = 0;
			for (int i = 0; i <= (pieceLength - 1); i++) {
				int start = startPiece * length;
				if (i < pieceLength - 1) {
					result[i] = new String(strArrayGBK, start, length);
				} else if (i == pieceLength - 1) {
					result[i] = new String(strArrayGBK, start,
							contentLength - start);
				} else {
					break;
				}
				startPiece++;
			}
		}
		return result;
	}

	public int getStringLength(String args) {
		float lengthCount = 0.0f;
		for (int i = 0; i < args.length(); i++) {
			char c = args.charAt(i);
			if (c < 256) { // 英文
				lengthCount += 0.5;
			} else { // 中文
				lengthCount += 1.0;
			}
		}
		System.out.println(Math.round(lengthCount));
		return Math.round(lengthCount);
	}

	/**
	 * 对输入的字符串进行字数截取
	 * 
	 * @param string
	 *            需要截取的字符串
	 * @param length
	 *            需要截取多少
	 * @return 截取后的字符串
	 */
	public static final String chopAtWord(String string, int length) {
		if (string == null || string.length() == 0) {
			return string;
		}
		char charArray[] = string.toCharArray();
		int sLength = string.length();
		if (length < sLength) {
			sLength = length;
		}
		for (int i = 0; i < sLength - 1; i++) {
			if (charArray[i] == '\r' && charArray[i + 1] == '\n') {
				return string.substring(0, i + 1);
			}
			if (charArray[i] == '\n') {
				return string.substring(0, i);
			}
		}

		if (charArray[sLength - 1] == '\n') {
			return string.substring(0, sLength - 1);
		}
		if (string.length() < length) {
			return string;
		}
		for (int i = length - 1; i > 0; i--) {
			if (charArray[i] == ' ') {
				return string.substring(0, i).trim();
			}
		}

		return string.substring(0, length);
	}

	/**
	 * 将传入的字符串进行MD5转化
	 * 
	 * @param data
	 *            需要转化的字符串
	 * @return 返回一个32位,进行加MD5加过密的字符串
	 */
	public static final synchronized String hash(String data) {
		if (digest == null) {
			try {
				digest = MessageDigest.getInstance("MD5");
			} catch (NoSuchAlgorithmException nsae) {
				System.out.println(
						"Failed to load the MD5 MessageDigest. Bright will be unable to function normally."
								+ nsae.toString());
			}
		}
		try {
			digest.update(data.getBytes("utf-8"));
		} catch (UnsupportedEncodingException e) {
			System.out.println(e);
		}
		return encodeHex(digest.digest());
	}

	/**
	 * 对传过的Byte数组,将其加工成一个16进的字符串
	 * 
	 * @param bytes
	 * @return
	 */
	public static final String encodeHex(byte bytes[]) {
		StringBuffer buf = new StringBuffer(bytes.length * 2);
		for (int i = 0; i < bytes.length; i++) {
			if ((bytes[i] & 0xff) < 16) {
				buf.append("0");
			}
			buf.append(Long.toString(bytes[i] & 0xff, 16));
		}

		return buf.toString();
	}

	/**
	 * 得到一个指定长的随机字符串
	 * 
	 * @param length
	 *            需要多长,
	 * @return 随机的字符串
	 */
	public static final String randomString(int length) {
		if (length < 1) {
			return null;
		}
		char randBuffer[] = new char[length];
		for (int i = 0; i < randBuffer.length; i++) {
			randBuffer[i] = numbersAndLetters[randGen.nextInt(71)];
		}

		return new String(randBuffer);
	}

	/**
	 * 将其传过的字符串变为可在html中显示原内容的字符串
	 * 
	 * @param in
	 *            原字符串
	 * @return 可现实原文的字符串
	 */
	public static final String escapeHTMLTags(String in) {
		if (in == null) {
			return null;
		}
		int i = 0;
		int last = 0;
		char input[] = in.toCharArray();
		int len = input.length;
		StringBuffer out = new StringBuffer((int) ((double) len * 1.3D));
		for (; i < len; i++) {
			char ch = input[i];
			if (ch <= '>') {
				if (ch == '<') {
					if (i > last) {
						out.append(input, last, i - last);
					}
					last = i + 1;
					out.append(LT_ENCODE);
				} else if (ch == '>') {
					if (i > last) {
						out.append(input, last, i - last);
					}
					last = i + 1;
					out.append(GT_ENCODE);
				}
			}
		}

		if (last == 0) {
			return in;
		}
		if (i > last) {
			out.append(input, last, i - last);
		}
		return out.toString();
	}

	// 下面的代码将字符串以正确方式显示（包括回车，换行，空格）
	public static String turn(String str) {
		while (str.indexOf("\n") != -1 && str.length() > 1) {
			str = str.substring(0, str.indexOf("\n")) + "<br>"
					+ str.substring(str.indexOf("\n") + 1);
		}
		while (str.length() > 1 && str.indexOf(" ") != -1
				|| str.indexOf(" ") != -1 || str.indexOf("　") != -1) {
			str = str.substring(0, str.indexOf(" ")) + "&nbsp;"
					+ str.substring(str.indexOf(" ") + 1);
		}

		return str;
	}

	// 下面的代码将字符串以正确方式显示（包括回车，换行，空格）
	public static String turnTextArea(String str) {
		for (int i = 0; i < str.length(); i++) {
			if (str.subSequence(i, i + 1).equals("\n")) {
				str = str.substring(0, i) + "<br>" + str.substring(i + 1);
			} else if (str.subSequence(i, i + 1).equals("　")
					|| str.subSequence(i, i + 1).equals(" ")
					|| str.subSequence(i, i + 1).equals(" ")) {
				str = str.substring(0, i) + "&nbsp;" + str.substring(i + 1);
			}
		}

		return str;
	}

	// 下面的代码将字符串以正确方式显示（包括回车，换行，空格）
	public static String turnTextArea1(String str) {
		for (int i = 0; i < str.length(); i++) {
			if (str.subSequence(i, i + 1).equals("<br>")
					|| str.subSequence(i, i + 1).equals("\r")) {
				str = str.substring(0, i) + "<br>" + str.substring(i + 1);
			} else if (str.subSequence(i, i + 1).equals("　")
					|| str.subSequence(i, i + 1).equals(" ")
					|| str.subSequence(i, i + 1).equals(" ")) {
				str = str.substring(0, i) + "&nbsp;" + str.substring(i + 1);
			}
		}

		return str;
	}

	public static String filter(String value) {

		if (value == null) {
			return (null);
		}

		StringBuffer result = new StringBuffer();
		for (int i = 0; i < value.length(); i++) {
			char ch = value.charAt(i);
			if (ch == '<') {
				result.append("&lt;");
			} else if (ch == '>') {
				result.append("&gt;");
			} else if (ch == '&') {
				result.append("&amp;");
			} else if (ch == '"') {
				result.append("&quot;");
			} else if (ch == '\r') {
				result.append("<BR>");
			} else if (ch == '\n') {
				if (i > 0 && value.charAt(i - 1) == '\r') {

				} else {
					result.append("<BR>");
				}
			} else if (ch == '\t') {
				result.append("&nbsp;&nbsp;&nbsp;&nbsp");
			} else if (ch == ' ') {
				result.append("&nbsp;");
			} else {
				result.append(ch);
			}
		}
		return (result.toString());
	}


	public static boolean isDigit(String str) {
		Pattern pattern = Pattern.compile("[0-9]+");
		Matcher matcher = pattern.matcher((CharSequence) str);
		return matcher.matches();

	}

	/**
	 * 检查非法字符如: \',\"
	 * 
	 * @param s
	 * @return
	 */
	public static boolean isValidateStr(String s) {
		if (s == null || s.length() < 1) {
			return false;
		}
		// /?><,!~|+=^&!
		char[] temp = { '\'', '\"' };
		boolean sign = true;
		for (int i = 0; i < s.length(); i++) {
			for (int j = 0; j < temp.length; j++) {
				if (s.charAt(i) == temp[j]) {
					sign = false;
					break;
				}
			}

		}
		return sign;
	}

	/*
	 * 取响应地址
	 */
	public static String requestAddr(HttpServletRequest request) {
		String query = request.getQueryString();
		String url = request.getRequestURL().toString();
		Enumeration enP = request.getParameterNames();

		// String param;
		// String params;
		// String paramsValue;
		boolean flag = false;
		/*
		 * for (param = ""; enP.hasMoreElements(); ) { params = (String)
		 * enP.nextElement(); paramsValue = request.getParameter(params); param
		 * = "&" + params + "="+ paramsValue; }
		 */
		if (enP.hasMoreElements()) {
			flag = true;
		}
		if (flag) {
			url = url + "?" + query;
		}

		return url;
	}

	/**
	 * 获取百分比
	 * 
	 * @param p1
	 * @param p2
	 * @return
	 */
	public static String percent(double p1, double p2) {
		String str;
		double p3 = p1 / p2;
		NumberFormat nf = NumberFormat.getPercentInstance();
		nf.setMinimumFractionDigits(2);
		str = nf.format(p3);
		return str;
	}

	/**
	 * 判断字符串的编码
	 * 
	 * @param str
	 * @return
	 */
	public static String getEncoding(String str) {
		String encode = "GB2312";
		try {
			if (str.equals(new String(str.getBytes(encode), encode))) {
				String s = encode;
				return s;
			}
		} catch (Exception exception) {
		}
		encode = "ISO-8859-1";
		try {
			if (str.equals(new String(str.getBytes(encode), encode))) {
				String s1 = encode;
				return s1;
			}
		} catch (Exception exception1) {
		}
		encode = "UTF-8";
		try {
			if (str.equals(new String(str.getBytes(encode), encode))) {
				String s2 = encode;
				return s2;
			}
		} catch (Exception exception2) {
		}
		encode = "GBK";
		try {
			if (str.equals(new String(str.getBytes(encode), encode))) {
				String s3 = encode;
				return s3;
			}
		} catch (Exception exception3) {
		}
		return "";
	}

	// 将 BASE64 编码的字符串 s 进行解码
	public static String getFromBASE64(String s) {
		if (s == null) {
			return null;
		}
		sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
		try {
			byte[] b = decoder.decodeBuffer(s);
			return new String(b);
		} catch (Exception e) {
			return null;
		}
	}

	public static String getBASE64(String s) {
		if (s == null) {
			return null;
		}

		String str = (new sun.misc.BASE64Encoder()).encode(s.getBytes());

		int i = 0;
		while (true) {
			if (str.indexOf("\n") >= 0) {
				i = str.indexOf("\n");
				str = str.substring(0, i - 1)
						+ str.substring(i + 1, str.length());

			} else {
				break;
			}
		}
		return str;
	}

	public static boolean allowAccess(HttpServletRequest request,
			String ipaccess, Byte allowVisit) {
		String currentPage = (String) request.getAttribute("CURSCRIPT");
		String action = request.getParameter("action");
		String memberIP = request.getRemoteAddr();
		boolean allowAccess = true;
		ipaccess = ipaccess != null ? ipaccess.trim() : "";

		if (allowVisit != null && allowVisit == 0
				&& !(currentPage.equals("member.jsp")
						&& (action != null && (action.equals("groupexpiry")
								|| action.equals("activate"))))) {
			allowAccess = false;
		}
		if (!ipaccess.equals("")) {
			String[] es = ipaccess.split("(\r|\n)");
			boolean sign = false;
			for (String e : es) {
				if (memberIP.startsWith(e)) {
					sign = true;
					break;
				}
			}
			allowAccess = sign;
		}
		return allowAccess;
	}

	/*
	 * 搜索关键字变红...
	 */
	public static String searchKeyRed(String str, String key1) {
		String name = "";
		if (key1 != null && !"".equals(key1)) {
			name = str.replace(key1, "<font color='red'>" + key1 + "</font>");
		} else {
			name = str;
		}
		return name;
	}

	/*
	 * 把Url传递的字符解码
	 */
	public static String uRLEncoder(String str, String charset) {
		try {
			if (str != null) {
				if (charset == null || charset.equals("")
						|| charset.equals("utf")) {
					str = java.net.URLEncoder.encode(str, "utf-8");
				} else {
					str = java.net.URLEncoder.encode(str, charset);
				}

			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return str;
	}

	/*
	 * 把Url传递的字符解码
	 */
	public static String uRLDecoder(String str, String charset) {
		try {
			if (str != null) {
				if (charset == null || charset.equals("")) {
					str = java.net.URLDecoder.decode(str, "utf-8");
				} else {
					str = java.net.URLDecoder.decode(str, charset);
				}
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return str;
	}

	/*
	 * 把Url传递的字符解码
	 */
	public static String uRLDecoder(String str) {
		try {
			str = java.net.URLDecoder.decode(str, "utf-8");

		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return str;
	}

	/*
	 * 获取字母序号
	 */
	public static String getCharacter(String type, int i) {
		String temp = "";
		if (i > 0 && i < 27) {
			if (type.equals("lower")) {

				temp = lowerLetters[i - 1] + "";
			} else {
				temp = upperLetters[i - 1] + "";
			}
		}
		return temp;
	}

	/**
	 * 取路径中文件夹名称．．．
	 */
	public static String getFolderName(String path, int flag) {
		String str = "";
		int index1 = 0; // 文件路径,最后一个"\"的位置...
		if (path.lastIndexOf("\\") == -1) {
			index1 = path.lastIndexOf("/");
		} else {
			index1 = path.lastIndexOf("\\");
		}
		String str1 = path.substring(0, index1); // 截取到文件夹名称末字符位置...

		int index2 = 0; // 截取到文件夹名称首字符位置...
		if (str1.lastIndexOf("\\") == -1) {
			index2 = str1.lastIndexOf("/");
		} else {
			index2 = str1.lastIndexOf("\\");
		}
		int length = str1.length(); // 字符长度...
		String str2 = str1.substring(index2 + 1, length);// 取文件夹名...

		if (flag == 1) {
			str = str1; // 不带的文件名的路径 示例：如：e:/abc/ab／a.txt 取：e:/abc/ab
		} else if (flag == 2) {
			str = str2; // 文件夹名 示例：e:/abc/ab／a.txt 取：ab
		} else {
			System.out.println("参数是1或2");
		}
		return str;
	}

	/**
	 * 取路径中文件名...
	 */
	public static String getFileName(String path, int flag) {

		int index1 = path.lastIndexOf("\\");
		int index2 = path.length();
		String str = "";
		String str1 = path.substring(index1 + 1, index2);

		int index3 = str1.lastIndexOf(".");
		int length = str1.length();
		String str2 = str1.substring(0, index3);
		String str3 = str1.substring(index3 + 1, length);
		if (flag == 1) { // 带扩展名的文件名...
			str = str1;
		} else if (flag == 2) { // 不带扩展名的文件名...
			str = str2;
		} else if (flag == 3) { // 取文件扩展名...
			str = str3;
		} else {
			System.out.println("参数是1-3");
		}

		return str;
	}

	/**
	 * 反序字符串...
	 */
	public static String getReverse(String str) {

		return new StringBuffer(str).reverse().toString();
	}

	/**
	 * 截取servlet中request.getServletPath()的名称.
	 */
	public static String getServletPathName(String selvletPath) {
		String name = "";
		int index = selvletPath.lastIndexOf(".");

		if (selvletPath.startsWith("/")) {
			name = selvletPath.substring(1, index);
		} else {
			name = selvletPath.substring(0, index);
		}
		return name;
	}

	/*
	 * 获取数据,为空则赋默认值
	 */
	public static String getString(String paramName, String defaultString) {
		String temp = "";
		if (paramName == null) {
			temp = defaultString;
		} else {
			temp = paramName;
		}
		return temp;
	}

	/*
	 * 获取数据,为空则赋默认值
	 */
	public static String getString(Object paramName, String defaultString) {
		String temp = "";
		if (paramName == null) {
			temp = defaultString;
		} else {
			temp = paramName.toString();
		}
		return temp;
	}

	/*
	 * 获取数据,为空则赋默认值
	 */
	public static int getInt(String paramName, int defaultInt) {
		int temp = 0;
		try {
			if (paramName == null) {
				temp = defaultInt;
			} else {
				temp = Integer.parseInt(paramName);
			}

		} catch (NumberFormatException e) {
			e.printStackTrace();
			return temp;
		}
		return temp;
	}

	/*
	 * 获取数据,为空则赋默认值
	 */
	public static long getLong(String paramName, long defaultInt) {
		long temp = 0;
		try {
			if (paramName == null) {
				temp = defaultInt;
			} else {
				temp = Long.parseLong(paramName);
			}

		} catch (NumberFormatException e) {
			e.printStackTrace();
			return temp;
		}
		return temp;
	}

	/*
	 * 获请服务器的域地址
	 */
	public static String basePath(HttpServletRequest request) {
		String path = "";

		if (request.getServerPort() == 80) {
			path = request.getScheme() + "://" + request.getServerName()
					+ request.getContextPath() + "/";

		} else {
			path = request.getScheme() + "://" + request.getServerName() + ":"
					+ request.getServerPort() + request.getContextPath() + "/";

		}
		return path;
	}

	/*
	 * 获取服务器的域地址
	 */
	public static String basePath(String serverName, int serverPort,
			String contextPath) {
		String url = "";

		if (serverPort == 80) {
			url = "http" + "://" + serverName;
		} else {
			url = "http" + "://" + serverName + ":" + serverPort;
		}

		if (contextPath != null && contextPath.startsWith("/")
				&& !"/".equals(contextPath)) {
			url = url + contextPath;
		}

		return url;
	}

	// 比较操作
	public static boolean cmpvalue(String cmptype, String cmpvalue1,
			String cmpvalue2) {
		int paramint1, paramint2;
		if (cmptype == null) {
			log.error("cmptype==null");
			return false;
		}
		if (cmptype.equalsIgnoreCase("==")) {
			// 比较是否相等
			if (cmpvalue1 == null || cmpvalue1.equalsIgnoreCase("null")) {
				cmpvalue1 = "";
			}
			if (cmpvalue2 == null || cmpvalue2.equalsIgnoreCase("null")) {
				cmpvalue2 = "";
			}
			if (StringUtil.isDigit(cmpvalue1)
					&& StringUtil.isDigit(cmpvalue2)) {
				paramint1 = Integer.parseInt(cmpvalue1);
				paramint2 = Integer.parseInt(cmpvalue2);
				return (paramint1 == paramint2);
			} else {
				if (cmpvalue1.equalsIgnoreCase(cmpvalue2)) {
					return true;
				} else {
					return false;
				}
			}
		} else if (cmptype.equalsIgnoreCase("!=")) {
			// 比较是否相等
			if (cmpvalue1 == null || cmpvalue1.equalsIgnoreCase("null")) {
				cmpvalue1 = "";
			}
			if (cmpvalue2 == null || cmpvalue2.equalsIgnoreCase("null")) {
				cmpvalue2 = "";
			}
			if (StringUtil.isDigit(cmpvalue1)
					&& StringUtil.isDigit(cmpvalue2)) {
				paramint1 = Integer.parseInt(cmpvalue1);
				paramint2 = Integer.parseInt(cmpvalue2);
				return (paramint1 != paramint2);
			} else {
				if (cmpvalue1.equalsIgnoreCase(cmpvalue2)) {
					return false;
				} else {
					return true;
				}
			}
		} else if (cmptype.equalsIgnoreCase(">")) {
			// 转换为数字
			if (StringUtil.isDigit(cmpvalue1)
					&& StringUtil.isDigit(cmpvalue2)) {
				paramint1 = Integer.parseInt(cmpvalue1);
				paramint2 = Integer.parseInt(cmpvalue2);
				return (paramint1 > paramint2);
			} else {
				log.error(
						"cmpvalue1 is not digit or cmpvalue2 is not digit,cmpvalue1="
								+ cmpvalue1 + ",cmpvalue2=" + cmpvalue2);
				return false;
			}
		} else if (cmptype.equalsIgnoreCase(">=")) {
			// 转换为数字
			if (StringUtil.isDigit(cmpvalue1)
					&& StringUtil.isDigit(cmpvalue2)) {
				paramint1 = Integer.parseInt(cmpvalue1);
				paramint2 = Integer.parseInt(cmpvalue2);
				return (paramint1 >= paramint2);
			} else {
				log.error(
						"cmpvalue1 is not digit or cmpvalue2 is not digit,cmpvalue1="
								+ cmpvalue1 + ",cmpvalue2=" + cmpvalue2);
				return false;
			}
		} else if (cmptype.equalsIgnoreCase("<")) {
			// 转换为数字
			if (StringUtil.isDigit(cmpvalue1)
					&& StringUtil.isDigit(cmpvalue2)) {
				paramint1 = Integer.parseInt(cmpvalue1);
				paramint2 = Integer.parseInt(cmpvalue2);
				return (paramint1 < paramint2);
			} else {
				log.error(
						"cmpvalue1 is not digit or cmpvalue2 is not digit,cmpvalue1="
								+ cmpvalue1 + ",cmpvalue2=" + cmpvalue2);
				return false;
			}
		} else if (cmptype.equalsIgnoreCase("<=")) {
			// 转换为数字
			if (StringUtil.isDigit(cmpvalue1)
					&& StringUtil.isDigit(cmpvalue2)) {
				paramint1 = Integer.parseInt(cmpvalue1);
				paramint2 = Integer.parseInt(cmpvalue2);
				return (paramint1 <= paramint2);
			} else {
				log.error(
						"cmpvalue1 is not digit or cmpvalue2 is not digit,cmpvalue1="
								+ cmpvalue1 + ",cmpvalue2=" + cmpvalue2);
				return false;
			}
		} else {
			log.error("not know cmptype:" + cmptype);
			return false;
		}
	}

	/*
	 * wap 将内容转码 转换成支持所有wap浏览器的编码 utf-8
	 */
	public static String WapEncode(String inPara) {
		char temChr;
		int ascChr;
		int i;
		String rtStr = new String("");
		if (inPara == null) {
			inPara = "";
		}
		for (i = 0; i < inPara.length(); i++) {
			temChr = inPara.charAt(i);
			ascChr = temChr + 0;
			// System.out.println(ascChr);
			// System.out.println(Integer.toBinaryString(ascChr));
			rtStr = rtStr + "&#x" + Integer.toHexString(ascChr) + ";";
		}
		return rtStr;
	}

	/*
	 * wap 将内容转换成正常形式下的内容
	 */
	public static String WapDecode(String theString) { // 解码
		char aChar;
		int len = theString.length();
		StringBuffer outBuffer = new StringBuffer(len);
		for (int x = 0; x < len;) {
			if ((theString.charAt(x) == '&') && (theString.charAt(x + 1) == '#')
					&& (theString.charAt(x + 2) == 'x')
					&& (theString.charAt(x + 7) == ';')) {
				// Read the xxxx
				x = x + 3;
				int value = 0;
				for (int i = 0; i < 4; i++) {
					aChar = theString.charAt(x++);
					switch (aChar) {
					case '0':
					case '1':
					case '2':
					case '3':
					case '4':
					case '5':
					case '6':
					case '7':
					case '8':
					case '9':
						value = (value << 4) + aChar - '0';
						break;
					case 'a':
					case 'b':
					case 'c':
					case 'd':
					case 'e':
					case 'f':
						value = (value << 4) + 10 + aChar - 'a';
						break;
					case 'A':
					case 'B':
					case 'C':
					case 'D':
					case 'E':
					case 'F':
						value = (value << 4) + 10 + aChar - 'A';
						break;
					default:
						throw new IllegalArgumentException(
								"Malformed &#Xaaaa encoding.");
					}
				} // END--for (int i=0; i<4; i++) {
				outBuffer.append((char) value);
				x++; // 跳过分号
			} else {
				outBuffer.append(theString.charAt(x++));
			} // END--if (aChar == '&') {
		} // END--for(int x=0; x<len; ) {
		return outBuffer.toString();
	}

	

	
	
	/*
	 * 分离字符串中的各变量
	 */
	public static String[] strSplit(String source, String split) {
		if (source == null || "".equals(source)) {
			return null;
		}
		StringTokenizer st = new StringTokenizer(source, split);
		int lenght = st.countTokens();

		String[] params = new String[lenght];
		for (int i = 0; st.hasMoreElements(); i++) {
			params[i] = ((String) st.nextElement()).trim();
		}
		return params;

	}

	/*
	 * 结果描述
	 */
	public static void printSplitResult(String[] rst) {
		for (int i = 0; rst != null && i < rst.length; i++) {
			log.info(i + ">" + rst[i].trim() + "|");
		}
	}

	/*
	 * 获取手机屏幕分频率
	 */
	public static String getPixel(HttpServletRequest request) {
		String screen = request.getHeader("x-up-devcap-screenpixels");
		String agent = request.getHeader("user-agent");

		// 以屏幕像素匹配
		if (screen != null) {
			return screen.replace(",", "_");
		}

		if (agent == null) {
			return "240_320";
		}

		// 加载机型数据
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("N900", "320_480");
		map.put("7600", "320_240");
		map.put("E68", "240_320");
		map.put("S900C", "480_640");
		map.put("A1800", "240_320");
		map.put("HTC6850", "480_640");
		map.put("HTC6950", "480_640");
		map.put("W799", "240_400");
		map.put("C362", "128_160");
		map.put("S60", "240_320");
		map.put("C7100", "240_320");
		map.put("V3c", "176_220");
		map.put("Z1", "240_320");
		map.put("S259", "128_160");
		map.put("C5600", "240_320");
		map.put("728", "240_320");
		map.put("D18", "240_320");
		map.put("W599", "240_320");
		map.put("C5100", "128_160");
		map.put("F6229", "240_320");
		map.put("S100", "240_320");
		map.put("C558", "240_320");
		map.put("X100", "128_128");
		map.put("CF58", "128_160");
		map.put("W579", "240_320");
		map.put("D780", "240_320");
		map.put("K2", "240_320");
		map.put("F126", "240_320");
		map.put("E200", "240_320");
		map.put("F639", "240_320");
		map.put("LG-KV755", "240_320");
		map.put("LG-KV500", "240_400");
		map.put("N68", "240_320");
		map.put("D90", "240_320");
		map.put("i329", "240_432");
		map.put("S505", "240_320");

		// 以终端机型匹配
		String pixel = null;
		Iterator it = map.keySet().iterator();
		while (it.hasNext()) {
			String key = (String) it.next();
			int index = agent.indexOf(key);
			if (index != -1) {
				pixel = map.get(key);
				break;
			}
		}

		pixel = (pixel == null) ? "240_320" : pixel;
		return pixel;
	}

	/*
	 * 获取手机屏幕分频率
	 */
	public static String getPixel(HttpServletRequest request,
			HashMap<String, String> map, String defalut_str) {
		String screen = request.getHeader("x-up-devcap-screenpixels");
		String agent = request.getHeader("user-agent");

		if (defalut_str == null || "".equals(defalut_str.trim())) {
			defalut_str = "240_320";
		}
		// 以屏幕像素匹配
		if (screen != null) {
			return screen.replace(",", "_");
		}

		if (agent == null) {
			return "240_320";
		}

		// 加载机型数据
		/*
		 * HashMap<String,String> map=new HashMap<String,String>();
		 * map.put("N900","320_480"); map.put("7600","320_240");
		 * map.put("E68","240_320"); map.put("S900C","480_640");
		 * map.put("A1800","240_320"); map.put("HTC6850","480_640");
		 * map.put("HTC6950","480_640"); map.put("W799","240_400");
		 * map.put("C362","128_160"); map.put("S60","240_320");
		 * map.put("C7100","240_320"); map.put("V3c","176_220");
		 * map.put("Z1","240_320"); map.put("S259","128_160");
		 * map.put("C5600","240_320"); map.put("728","240_320");
		 * map.put("D18","240_320"); map.put("W599","240_320");
		 * map.put("C5100","128_160"); map.put("F6229","240_320");
		 * map.put("S100","240_320"); map.put("C558","240_320");
		 * map.put("X100","128_128"); map.put("CF58","128_160");
		 * map.put("W579","240_320"); map.put("D780","240_320");
		 * map.put("K2","240_320"); map.put("F126","240_320");
		 * map.put("E200","240_320"); map.put("F639","240_320");
		 * map.put("LG-KV755","240_320"); map.put("LG-KV500","240_400");
		 * map.put("N68","240_320"); map.put("D90","240_320");
		 * map.put("i329","240_432"); map.put("S505","240_320");
		 */

		// 以终端机型匹配
		String pixel = null;
		if (map != null) {
			Iterator it = map.keySet().iterator();
			while (it.hasNext()) {
				String key = (String) it.next();
				int index = agent.indexOf(key);
				if (index != -1) {
					pixel = map.get(key);
					break;
				}
			}
		}

		pixel = (pixel == null) ? defalut_str : pixel;
		return pixel;
	}

	/*
	 * 通用防SQL注入函数
	 */
	public static boolean sql_inj(String str) {
		String inj_str = "'|and|exec|insert|select|delete|update|count|*|%|chr|mid|master|truncate|char|declare|user|dbo|;|or|-|+|,|1=1";

		StringTokenizer st = new StringTokenizer(inj_str, "|");
		int lenght = st.countTokens();
		String inj_stra[] = new String[lenght];

		for (int i = 0; st.hasMoreElements(); i++) {
			inj_stra[i] = (String) st.nextElement();
			// System.out.println(inj_stra[i].trim()+"|");
		}

		for (int i = 0; i < inj_stra.length; i++) {
			if (str.indexOf(inj_stra[i]) >= 0) {
				return true;
			}
		}
		return false;
	}

	/*
	 * 过滤html标签
	 */
	public static String Html2Text(String inputString) {
		String htmlStr = inputString; // 含html标签的字符串
		String textStr = "";

		java.util.regex.Pattern p_script;
		java.util.regex.Matcher m_script;
		java.util.regex.Pattern p_style;
		java.util.regex.Matcher m_style;
		java.util.regex.Pattern p_html;
		java.util.regex.Matcher m_html;

		try {
			String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>"; // 定义script的正则表达式{或<script[^>]*?>[\\s\\S]*?<\\/script>
			// }
			String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>"; // 定义style的正则表达式{或<style[^>]*?>[\\s\\S]*?<\\/style>
			// }
			String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式

			p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
			m_script = p_script.matcher(htmlStr);
			htmlStr = m_script.replaceAll(""); // 过滤script标签

			p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
			m_style = p_style.matcher(htmlStr);
			htmlStr = m_style.replaceAll(""); // 过滤style标签

			p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
			m_html = p_html.matcher(htmlStr);
			htmlStr = m_html.replaceAll(""); // 过滤html标签

			textStr = htmlStr;

		} catch (Exception e) {
			System.err.println("Html2Text: " + e.getMessage());
		}

		return textStr;// 返回文本字符串
	}

	public static String hex2Str(String theHex) {
		String theRst = "";
		byte[] theByte = new byte[theHex.length() / 2];

		try {
			for (int i = 0; i < theHex.length(); i += 2) {
				theByte[i / 2] = Integer
						.decode("0X" + theHex.substring(i, i + 2)).byteValue();
			}
			theRst = new String(theByte, 0, theByte.length, "Shift_JIS");
		} catch (Exception Ue) {
			Ue.printStackTrace();
		}
		return theRst;
	}

	public static String str2Hex(String theStr) {
		byte[] bytes;
		String result = "";
		int tmp;
		String tmpStr;
		try {
			bytes = theStr.getBytes("Shift_JIS");
			for (int i = 0; i < bytes.length; i++) {
				if (bytes[i] < 0) {
					tmp = 256 + bytes[i];
					tmpStr = Integer.toHexString(tmp).toUpperCase();
					result += tmpStr;
				} else {
					tmpStr = Integer.toHexString(bytes[i]).toUpperCase();

					result += tmpStr.length() == 1 ? "0" + tmpStr : tmpStr;
				}
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

	public static String replace(final String sourceString, Object[] object) {
		String temp = sourceString;
		for (int i = 0; i < object.length; i++) {
			String[] result = (String[]) object[i];
			System.out.println(result[0]);
			Pattern pattern = Pattern.compile(result[0]);
			Matcher matcher = pattern.matcher(temp);
			temp = matcher.replaceAll(result[1]);
		}
		return temp;
	}

	/**
	 * 名字以*代替
	 */
	public static String hiddenName(String name) {
		if (name == null || name.length() == 0) {
			return "";
		}
		int len = name.length();
		if (len >= 3) {
			name = START + name.substring(1, len - 1) + START;
		} else if (len == 2) {
			name = START + name.substring(1);
		} else {
			return START;
		}
		return name;

	}

	/*
	 * 订单流水用*代替
	 */
	public static String hideOrderId(Long id) {
		if (id == 0L || id < 100) {
			return id + "";
		}
		String str = String.valueOf(id);
		StringBuffer strAp = new StringBuffer();
		strAp.append(str.substring(0, 2)).append("********");
		if (str.length() < 10) {
			return strAp.toString();
		}
		strAp.append(str.substring(10));
		return strAp.toString();
	}

	/*
	 * 银行账号用*代替
	 */
	public static String hideBankCard(String bankAccount) {
		int len = bankAccount.length();
		StringBuffer append = new StringBuffer();
		if (bankAccount == null || len == 0) {
			return "";
		}
		if (len > 4) {
			append.append(bankAccount.substring(0, 4)).append("********");
		}
		if (len > 12) {
			append.append(bankAccount.substring(12));
		}

		return append.toString();

	}
	


	public static String subTextString(String str, int len) {
		if (str.length() < len / 2) {
			return str;
		}
		int count = 0;
		StringBuilder sb = new StringBuilder();
		String[] ss = str.split("");
		for (int i = 1; i < ss.length; i++) {
			count += ss[i].getBytes().length > 1 ? 2 : 1;
			sb.append(ss[i]);
			if (count >= len-2){
				sb.append("…");
				break;
			}
		}
		// 不需要显示...的可以直接return sb.toString();
		return (sb.length() < str.length())
				? sb.toString() : str;
	}
	//随机数的生成
	public static String getRandNum(int charCount) {
		String charValue = "";
		for (int i = 0; i < charCount; i++) {
			char c = (char) (randomInt(0, 10) + '0');
			charValue += String.valueOf(c);
		}
		return charValue;
	}
	
	/**
	 * 发送短信
	 * 
	 * @param name			用户名
	 * @param pwd			密码
	 * @param mobileString	电话号码字符串，中间用英文逗号间隔
	 * @param contextString	内容字符串
	 * @param sign			签名
	 * @param stime			追加发送时间，可为空，为空为及时发送
	 * @param extno			扩展码，必须为数字 可为空
	 * @return				
	 * @throws Exception
	 */
    public static String doPost(String name, String pwd, 
    		StringBuffer mobileString, StringBuffer contextString,
    		String sign, String stime, StringBuffer extno) throws Exception {
    	StringBuffer param = new StringBuffer();
    	param.append("name="+name);
    	param.append("&pwd="+pwd);
    	param.append("&mobile=").append(mobileString);
    	param.append("&content=").append(URLEncoder.encode(contextString.toString(),"UTF-8"));
    	param.append("&stime="+stime);
    	param.append("&sign=").append(URLEncoder.encode(sign,"UTF-8"));
    	param.append("&type=pt");
    	param.append("&extno=").append(extno);
        
        URL localURL = new URL("http://web.daiyicloud.com/asmx/smsservice.aspx?");
        URLConnection connection = localURL.openConnection();
        HttpURLConnection httpURLConnection = (HttpURLConnection)connection;
        
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
        httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        httpURLConnection.setRequestProperty("Content-Length", String.valueOf(param.length()));
        
        OutputStream outputStream = null;
        OutputStreamWriter outputStreamWriter = null;
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        String resultBuffer = "";
        
        try {
            outputStream = httpURLConnection.getOutputStream();
            outputStreamWriter = new OutputStreamWriter(outputStream);
            
            outputStreamWriter.write(param.toString());
            outputStreamWriter.flush();
            
            if (httpURLConnection.getResponseCode() >= 300) {
                throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
            }
            
            inputStream = httpURLConnection.getInputStream();
            resultBuffer = convertStreamToString(inputStream);
            
        } finally {
            
            if (outputStreamWriter != null) {
                outputStreamWriter.close();
            }
            
            if (outputStream != null) {
                outputStream.close();
            }
            
            if (reader != null) {
                reader.close();
            }
            
            if (inputStreamReader != null) {
                inputStreamReader.close();
            }
            
            if (inputStream != null) {
                inputStream.close();
            }
            
        }

        return resultBuffer;
    }
	
	
	/**
	 * 转换返回值类型为UTF-8格式.
	 * @param is
	 * @return
	 */
	public static String convertStreamToString(InputStream is) {    
        StringBuilder sb1 = new StringBuilder();    
        byte[] bytes = new byte[4096];  
        int size = 0;  
        
        try {    
        	while ((size = is.read(bytes)) > 0) {  
                String str = new String(bytes, 0, size, "UTF-8");  
                sb1.append(str);  
            }  
        } catch (IOException e) {    
            e.printStackTrace();    
        } finally {    
            try {    
                is.close();    
            } catch (IOException e) {    
               e.printStackTrace();    
            }    
        }    
        return sb1.toString();    
    }
	public static int randomInt(int from, int to) {
		Random r = new Random();
		return from + r.nextInt(to - from);
	}
	public static void main(String[]args){
// 随机数的生成
		String randNum = StringUtil.getRandNum(4);
		String content="您正在进行微信关联会员操作，短信验证码为"+randNum+"，请确保本人操作并保密！【广州金鹏社工】";
		String sign="广州金鹏社工";
		try {
			// 用户名
			String name="jinpeng"; 
			// 密码
			String pwd="26160F0578884622384A19D03344"; 
			// 电话号码字符串，中间用英文逗号间隔
			StringBuffer mobileString=new StringBuffer("15626437039");
			// 内容字符串
			StringBuffer contextString=new StringBuffer(content);
			// 扩展码，必须为数字 可为空
			StringBuffer extno=new StringBuffer();
			StringUtil.doPost(name, pwd, mobileString, contextString, sign, "", extno);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 提取微信名字，去除特定符号.
	 * 
	 * @param str
	 * @return
	 */
	public static String dofilter(String str) {
		String str_Result = "", str_OneStr = "";
		for (int z = 0; z < str.length(); z++) {
			str_OneStr = str.substring(z, z + 1);
			if (str_OneStr.matches("[\u4e00-\u9fa5]+")
					|| str_OneStr.matches("[\\x00-\\x7F]+")) {
				str_Result = str_Result + str_OneStr;
			}
		}
		return str_Result;
	}
}
